<?php

namespace Beerus\Modules\Designer\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use Beerus\Modules\Designer\Actions\SaleSend\Info;
use Beerus\Modules\Designer\Actions\SaleSend\Submit;
use Doraemon\model\Designer;
use Doraemon\model\Designer\DesignerAuthSendMsg;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form\Tools;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\MultipleSteps;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Grid\Displayers\DropdownActions;

use Doraemon\model\AdmDesignerGlory;
use Doraemon\model\AdmSaleBind\AdmSaleBind;
use Doraemon\model\Member;
use Doraemon\service\admin\SaleBind;
use Beerus\Modules\Designer\Actions\Unbind;
use Biz\pockets\excel\DownExcel;

/**
 * 销售认领用户管理
 */
class SaleController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // 列表
    public function index(Request $request, Content $content)
    {
        //参数
        $url = $_SERVER["REQUEST_URI"];
        $data_url = explode('?', $url);
        $export_url = $data_url[1] ?: '';

        $request_data = $request->all();
        $pageSize = $request->input("per_page", self::PAGE_SIZE);
        $request_data = self::_filterWhere($request_data);
        $and = (array)$request_data['AND'];
        $and['data_status'] = AdmSaleBind::STATUS_NORMAL;
        $limitArr = $request_data['LIMIT'];
        $params = [
            'ORDER' => ['edittime' => 'ASC'],
            'LIMIT' => $limitArr,
        ];
        if ($and) {
            $params['AND'] = $and;
        }
        $itemLiist = AdmSaleBind::select('*', $params);
        $total = AdmSaleBind::count('*', $and);
        $gridModel = new pGridDataModel($itemLiist, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $export_url) {
                $grid->setActionClass(DropdownActions::class);
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', 'Uid');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('admin_name', '销售用户名');
                        // $filter->equal('data_status', '状态')->select(AdmSaleBind::STATUS_DESC);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('edittime', '认领时间')->date('Y-m-d');
                    });
                    $filter->expand();
                });

                // 添加导出按钮
                $grid->tools(function (Grid\Tools $tool) use ($grid, $export_url) {
                    $url = url('/admin/Designer/sale/exportData?' . $export_url);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="' . $url . '">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出</span></a>
                    </div>';
                    $tool->append($button);
                });

                $grid->column("id", 'ID');
                $grid->column("uid", 'Uid');
                $grid->column("nick", '昵称')->display(function () {
                    $userinfo = Member::getUser($this->uid);
                    return $userinfo['nick'];
                });
                $grid->column("admin_name", '销售用户名');
                $grid->column("days", '认领天数')->display(function () {
                    return floor((time() - $this->edittime) / 3600 / 24);
                });
                $grid->column("edittime", '认领时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->edittime);
                });
                $grid->column("data_status", '状态')
                    ->using(AdmSaleBind::STATUS_DESC)
                    ->label([
                        AdmSaleBind::STATUS_NORMAL => 'success',
                        AdmSaleBind::STATUS_DELETE => 'danger',
                    ]);

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                    $actions->add(new Unbind);
                });
            });

        $tab = new Tab();
        $tab->add('销售认领用户列表', $gridList->render());
        $tab->addLink('下行发送记录', '/admin/Designer/sale/sendList');
        $content->row($tab);
        return $content
            ->header('销售认领用户列表')
            ->description(' ')
            ->breadcrumb(['text' => '销售认领用户列表']);
    }

    // 编辑
    public function edit(Request $request, Content $content, $id = 0)
    {
        $request = $request->all();
        if ($id == 0) {
            return $content
                ->header('设计师荣耀值 - 编辑')
                ->breadcrumb([
                    'text' => '设计师荣耀值',
                    'url' => '/Designer/glory/',
                ])
                ->body(self::editAction($request, $id, True));
        } else {
            return $content
                ->header('设计师荣耀值 - 编辑')
                ->breadcrumb([
                    'text' => '设计师荣耀值',
                    'url' => '/Designer/glory/',
                ])
                ->body(self::editAction($request, $id, False));
        }
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if (!$isCreate) {
            $data = AdmDesignerGlory::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $data = [];
            $form = new Form($data);
        }

        $form->text('uid', 'Uid')->setWidth(4, 2)->required('不能为空')
            ->help("内部测试号必须用142注册，金额输入0即可；用142注册的内部测试号，无需填写回单编号和上传付款凭证");
        $form->select('package_id', '套餐类型')->setWidth(4, 2)->options(AdmDesignerGlory::PACKAGE_DESC);
        $form->select('pay_platform', '支付方式')->setWidth(4, 2)->options(AdmDesignerGlory::PAY_PLATFORM_DESC);
        $form->text('dsn', '荣耀值号')->setWidth(4, 2)->required('不能为空');
        $form->select('pay_status', '支付状态')->setWidth(4, 2)->options(AdmDesignerGlory::PAY_STATUS_DESC);
        $form->text('real_price', '实付金额')->setWidth(4, 2)->required('不能为空');
        $form->text('certificate_number', '付款凭证编号')->setWidth(4, 2);

        $form->action('/admin/DecoCompany/order/save');

        return $form->render();
    }

    // 提交
    public function editSubmit(Request $request)
    {
        $request = $request->all();

        $dsn_exist = AdmDesignerGlory::getByDsn($request['dsn']);
        if (!isset($request['id']) && $dsn_exist) {
            throw new InputErrorException('荣耀值号已存在', 403, 'dsn');
        }

        $data = [
            'dsn' => $request['dsn'],
            'uid' => $request['uid'],
            'package_id' => $request['package_id'],
            'package_name' => AdmDesignerGlory::PACKAGE_DESC[$request['package_id']],
            'pay_platform' => $request['pay_platform'],
            'pay_status' => $request['pay_status'],
            'certificate_number' => $request['certificate_number'],
            'certificate_number_pic' => $request['certificate_number_pic'] ?: '',
            'real_price' => $request['real_price'],
            'product_price' => $request['real_price'],
        ];

        $now = time();
        if (isset($request['id'])) {
            $data['update_time'] = $now;
            $id = $request['id'];

            $rs = AdmDesignerGlory::updateOrder($id, $data);
        } else {
            $data['pay_time'] = $now;
            $rs = AdmDesignerGlory::createOrder($data);
        }

        if ($rs) {
            if (isset($request['id'])) {
                $title = '修改成功';
            } else {
                $title = '添加成功';
            }

            $success = new MessageBag([
                'title' => $title
            ]);
            return redirect('/admin/DecoCompany/order')->with(compact('success'));
        } else {
            if (isset($request['id'])) {
                $title = '修改失败';
            } else {
                $title = '添加失败';
            }
            $error = new MessageBag([
                'title' => $title
            ]);
            return back()->with(compact('error'));
        }
    }

    private function _filterWhere($params)
    {
        if (isset($params['_columns_'])) {
            unset($params['_columns_']);
        }
        if (isset($params['_pjax'])) {
            unset($params['_pjax']);
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);
        unset($params['per_page']);

        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                if ($_k <> 'edittime') {
                    $where[$_k] = $_v;
                } else {
                    if (!empty($_v['start'])) {
                        $where["edittime[>=]"] = strtotime($_v['start'] . ' 00:00:00');
                    }
                    if (!empty($_v['end'])) {
                        $where["edittime[<=]"] = strtotime($_v['end'] . ' 23:59:59');
                    }
                }

            }
        }
        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    /*导出数据
    *
    * */
    public function exportData(Request $request)
    {
        $request_data = $request->all();
        $request_data = self::_filterWhere($request_data);
        $and = (array)$request_data['AND'];
        $and['data_status'] = AdmSaleBind::STATUS_NORMAL;
        $params = [
            'ORDER' => ['edittime' => 'ASC'],
        ];
        if ($and) {
            $params['AND'] = $and;
        }
        $result = AdmSaleBind::select('*', $params);
        $list = [];
        if ($result && is_array($result)) {
            foreach ($result as $val) {
                $userinfo = Member::getUser($val['uid']);
                $nick = $userinfo['nick'];
                $days = floor((time() - $val['edittime']) / 3600 / 24);
                $status = AdmSaleBind::STATUS_DESC[$val['data_status']];
                $list[] = [
                    'id' => $val['id'],
                    'uid' => $val['uid'],
                    'nick' => $nick,
                    'admin_name' => $val['admin_name'],
                    'day' => $days,
                    'edittime' => date("Y-m-d H:i:s", $val['edittime']),
                    'data_status' => $status,
                ];
            }
        }
        $reason = '销售认领用户列表';
        $header = ['ID', 'Uid', '昵称', '销售用户名', '认领天数', '认领时间', '状态'];
        $letter = range('A', 'G');
        $excelObj = new DownExcel();
        $excelObj->setFileName($reason);
        $excelObj->setSheetTitle($reason);

        //设置列宽
        $widths = ['C' => 30, 'D' => 30, 'E' => 30, 'F' => 30, 'G' => 30, 'H' => 30, 'I' => 30];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->setTextFormat('C');
        foreach ($header as $key => $value) {
            //设置字体
            $excelObj->setFrontName($letter[$key]);
            //设置加粗
            $excelObj->setFrontBold("$letter[$key]1");
            //设置大小
            $excelObj->setFrontSize($letter[$key]);
        }
        $excelObj->create($list, $header);
    }

    /**
     * @Notes: 销售发送下行
     * @param Content $content
     * @return Content
     * @author: weiyizheng
     * @Time: 2022/4/7   4:29 下午
     */
    public function sendMsg(Content $content)
    {
        $steps = [
            'info' => Info::class,
            'submit' => Submit::class
        ];

        $makeStep = MultipleSteps::make($steps);

        return $content->header('发送系统下行')->title("发送系统下行")->breadcrumb([
            'text' => '销售认领用户列表',
            'url' => '/sale',
        ])->body($makeStep);
    }

    /**
     * @Notes: 下行消息发送记录
     * @param Request $request
     * @param Content $content
     * @return Content
     * @author: weiyizheng
     * @Time: 2022/4/7   4:36 下午
     */
    public function sendList(Request $request, Content $content)
    {
        $request_data = $request->all();
        $page_size = $request->input('per_page', 10);
        $page = $request->input('page', 1);

        $condition = array();

        if ($request_data['uid']) {
            $condition['to_uid'] = $request_data['uid'];
        }
        if ($request_data['admin_name']) {
            $condition['admin_name'] = $request_data['admin_name'];
        }
        if ($request_data['send_time']) {
            if ($request_data['send_time']['start']) {
                $condition['send_time[>=]'] = $request_data['send_time']['start'];
            }
            if ($request_data['send_time']['end']) {
                $condition['send_time[<=]'] = $request_data['send_time']['end'] . " 23:59:59";
            }
        }
        $total = DesignerAuthSendMsg::count($condition);

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $itemLiist = DesignerAuthSendMsg::select('*', $condition);
        $gridModel = new pGridDataModel($itemLiist, $total, [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->setActionClass(DropdownActions::class);
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->tools(function ($tools) {
                    $url = url('/admin/Designer/sale/send');
                    $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-success" title="发送下行" target="" href="' . $url . '"><i class="fa fa-plus"></i><span class="hidden-xs">发送下行</span></a>
</div>';
                    $tools->append($button);
                });

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', '发送目标UID');
                        $filter->equal('admin_name', '操作人');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('send_time', '发送时间')->date('Y-m-d');
                    });
                    $filter->expand();
                });

                $grid->column("id", 'ID')->display(function () {
                    return "<a href='https://frieza.haohaozhu.me/admin/sysmsg/index?&from_uid=&to_uid={$this->to_uid}&msg_code=" . DesignerAuthSendMsg::MSG_CODE . "' target='_blank'>" . $this->id . "</a>";
                });
                $grid->column("to_uid", '发送目标UID');
                $grid->column("nick", '发送目标昵称')->display(function () {
                    $userinfo = Member::getUser($this->to_uid);
                    return $userinfo['nick'];
                });
//                $grid->column("from_uid", '发送人UID');
                $grid->column("template_type", '发送的认证类型')->display(function () {
                    return Info::SEND_TEMPLATE[$this->template_type];
                });
                $grid->column("send_time", '发送时间');
//                $grid->column("link", '发送的认证地址');
                $grid->column("admin_name", '操作人');

                $grid->disableActions();
            });

        $tab = new Tab();
        $tab->addLink('销售认领用户列表', '/admin/Designer/sale');
        $tab->add('下行发送记录', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('下行发送记录')
            ->description('')
            ->breadcrumb(['text' => '销售认领用户列表']);
    }
}
